package com.jl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.quartz.QuartzManager;
import com.jl.commons.quartz.job.AddInspectionTaskJob;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.BASE64;
import com.jl.model.CycleTask;
import com.jl.service.ICycleTaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 江剑
 */
@Controller
@RequestMapping("/cycleTask")
public class CycleTaskController extends BaseController {

    @Autowired
    private ICycleTaskService cycleTaskService;

    @Autowired
    private QuartzManager quartzManager;

    @GetMapping("/cycleTaskDataGrid")
    @RequiresPermissions("/cycleTask/cycleTaskDataGrid")
    public String cycleTaskList(){
        return "cycleTask_list";
    }

    @GetMapping("/detail")
    @RequiresPermissions("/cycleTask/detail")
    public String CycleTaskDetailPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "cycleTask_detail";
    }


    @GetMapping("/add")
    @RequiresPermissions("/cycleTask/add")
    public String addCycleTaskPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "cycleTask_add";
    }

    @PostMapping("/add")
    @RequiresPermissions("/cycleTask/add")
    @ResponseBody
    public ResultData addCycleTask(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        CycleTask cycleTask = JSON.parseObject(value,CycleTask.class);
        //判断编号是不是自己的，如果是自己的则表示可以修改
        boolean used = cycleTaskService.isCycleTaskNameUsed(cycleTask.getName());
        if(used){
            return fail(ErrorCode.CYCLY_TASK_NAME_USED,ErrorMessage.CYCLY_TASK_NAME_USED);
        }
        cycleTask.setCreateId(getUserId());
        cycleTask.setGmtCreate(new Date());
        if(cycleTaskService.save(cycleTask)){
            //加入调度
            quartzManager.addInspectionTaskJob(cycleTask);
        }else{
            return fail(ErrorCode.CYCLY_TASK_ADD_ERROR,ErrorMessage.CYCLY_TASK_ADD_ERROR);
        }

        return success(cycleTask);
    }

    @GetMapping("/edit")
    @RequiresPermissions("/cycleTask/edit")
    public String editCycleTaskPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "cycleTask_add";
    }

    @PostMapping("/edit")
    @RequiresPermissions("/cycleTask/edit")
    @ResponseBody
    public ResultData editCycleTask(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        CycleTask cycleTask = JSON.parseObject(value,CycleTask.class);
        //id存在表示是更新数据
        cycleTask.setGmtModified(new Date());
        cycleTask.setModifyId(getUserId());
        if(cycleTaskService.updateById(cycleTask)){
            //修改调度内容
            quartzManager.editInspectionTaskJob(cycleTask);
        }else{
            return fail(ErrorCode.CYCLY_TASK_EDIT_ERROR,ErrorMessage.CYCLY_TASK_EDIT_ERROR);
        }

        return success(cycleTask);
    }

    @PostMapping("/delete")
    @RequiresPermissions("/cycleTask/delete")
    @ResponseBody
    public ResultData deletesCycleTask(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value,Long.class);
        //同时删除所有的调度
        QueryWrapper<CycleTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        List<CycleTask> cycleTasks = cycleTaskService.list(queryWrapper);
        for(CycleTask cycleTask : cycleTasks){
            quartzManager.removeJob(cycleTask.getName(), AddInspectionTaskJob.class.getName(),cycleTask.getName(),AddInspectionTaskJob.class.getName());
        }
        boolean b = cycleTaskService.removeByIds(ids);
        if(b){
            return success();
        }
        return fail();
    }

    @PostMapping("/dataGrid")
    @RequiresPermissions("/cycleTask/dataGrid")
    @ResponseBody
    public ResultData cycleTaskDataGrid(Long current,Long pageSize,String searchCol,String searchValue,String json){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<CycleTask> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(json)){
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(StringUtils.isNotBlank(jsonObject.getString("name"))){
                queryWrapper.like("t.name",jsonObject.getString("name"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("description"))){
                queryWrapper.like("t.description",jsonObject.getString("description"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("planTime"))){
                queryWrapper.like("t.plan_time",jsonObject.getString("planTime"));
            }
            if(null!=jsonObject.getLong("modelId") && jsonObject.getLong("modelId")!=0){
                queryWrapper.eq("t.model_id",jsonObject.getString("modelId"));
            }
            if(null!=jsonObject.getLong("operatorId") && jsonObject.getLong("operatorId")!=0){
                queryWrapper.eq("t.operator_id",jsonObject.getString("operatorId"));
            }
            if(null!=jsonObject.getInteger("cycleType") && jsonObject.getInteger("cycleType")!=0){
                queryWrapper.eq("t.cycle_type",jsonObject.getString("cycleType"));
            }
        }else{
            if(StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)){
                if(searchCol.equals(Constants.ID)){
                    queryWrapper.eq("t.id",searchValue);
                }else{
                    queryWrapper.like("t."+searchCol,searchValue);
                }
            }
        }

        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        cycleTaskService.selectCycleTaskDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }

}